<template>
  <view class="container">
    <!-- 顶部切换 -->
    <u-subsection :list="['上月消费', '往期账单']" :current="activeTab" @change="handleTabChange" mode="button"
      activeColor="#2979ff" bgColor="#f8f8f8"></u-subsection>

    <!-- 消费明细 -->
    <view class="content">
      <!-- 上月消费 -->
      <template v-if="activeTab === 0">
        <u-cell-group>
          <u-cell v-for="(item, index) in currentBills" :key="index" :title="`${item.yearMonth}月账单`"
            :value="`¥${item.totalCost.toFixed(2)}`">
            <view slot="label">
              <view class="detail-item">
                <text>护理费：¥{{ item.nursingCost.toFixed(2) }}</text>
                <text>住宿费：¥{{ item.stayCost.toFixed(2) }}</text>
              </view>
              <view class="detail-item">
                <text>餐饮费：¥{{ item.foodCost.toFixed(2) }}</text>
                <text>特殊费用：¥{{ item.specialCost.toFixed(2) }}</text>
              </view>
              <view class="remark">备注：{{ item.remark || '无' }}</view>
              <view class="balance-status">
                账户状态：{{ item.balance < 0 ? '待支付' : '已缴清' }} </view>
              </view>
          </u-cell>
        </u-cell-group>
        <!-- 去支付 -->
     <!--   <u-button type="primary" :text="paymentButtonText" @click="handlePayment" class="pay-button"
          :disabled="isPaymentDisabled"></u-button> -->
      </template>

      <!-- 往期账单 -->
      <template v-else>
        <u-cell-group>
          <u-cell v-for="(item, index) in historyBills" :key="index" :title="`${item.yearMonth}月账单 - ${item.billNo}`"
            :value="`¥${item.totalCost.toFixed(2)}`" isLink @click="showBillDetail(item)">
            <view slot="label">
              <text class="time">{{ formatDate(item.paymentDate) }}</text>
              <view class="detail-item">
                <text>护理费：¥{{ item.nursingCost.toFixed(2) }}</text>
                <text>住宿费：¥{{ item.stayCost.toFixed(2) }}</text>
              </view>
            </view>
          </u-cell>
        </u-cell-group>
      </template>
    </view>

    <!-- 账单详情弹窗 -->
    <u-popup :show="showDetail" mode="center" round="16" @close="closeShowDetail">
      <view class="popup-content" v-if="currentBill">
        <u--text :text="`${currentBill.yearMonth}月账单详情`" size="18" bold class="title"></u--text>
        <view class="detail-list">
          <u-text prefixIcon="账单编号-->" :text="currentBill.billNo" />
          <u-text prefixIcon="总金额-->" :text="'¥' + currentBill.totalCost.toFixed(2)" />
          <u-text prefixIcon="护理费-->" :text="'¥' + currentBill.nursingCost.toFixed(2)" />
          <u-text prefixIcon="住宿费-->" :text="'¥' + currentBill.stayCost.toFixed(2)" />
          <u-text prefixIcon="餐饮费-->" :text="'¥' + currentBill.foodCost.toFixed(2)" />
          <u-text prefixIcon="特殊费用-->" :text="'¥' + currentBill.specialCost.toFixed(2)" />
          <u-text prefixIcon="生成时间-->" :text="formatDate(currentBill.paymentDate)" />
          <u-text prefixIcon="备注-->" :text="currentBill.remark || '无'" />
          <u-text prefixIcon="账户余额-->" :text="'¥' + currentBill.balance.toFixed(2)" />
        </view>
      </view>
    </u-popup>

    <!-- 新增充值按钮 -->
    <u-button type="primary" text="充值/查询余额" icon="rmb-circle-fill" shape="circle" class="recharge-btn"
      @click="showRecharge = true"></u-button>


    <!-- 新增充值弹窗 -->
    <u-popup :show="showRecharge" mode="center" round="16" @close="showRecharge = false">
      <view class="recharge-popup">
        <u--text text="充值金额" size="18" bold class="title"></u--text>
        <!-- 新增余额显示 -->
        <u--text :text="`当前余额：¥${accountBalance.toFixed(2)}`" size="16" color="#606266" class="balance-text"></u--text>
        <u-input v-model="rechargeAmount" type="number" placeholder="单笔充值不高于1万元" clearable class="input-amount">
          <template #prefix>
            <u--text text="¥" marginRight="10"></u--text>
          </template>
        </u-input>
        <u--text v-if="amountError" :text="amountError" color="#f56c6c" size="12"></u--text>

        <u-button type="primary" text="去支付" @click="handleRecharge" class="confirm-btn"></u-button>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getAllFeeDetails, payBillOrRecharge } from "../feeDetails/feeDetailsApi"
export default {
  data() {
    return {
      // 新增账户余额字段
      accountBalance: 0.0,
      currentBills: [],
      historyBills: [],
      activeTab: 0,
      showDetail: false,
      currentBill: null,
      showRecharge: false,    // 新增充值弹窗状态
      rechargeAmount: null,     // 新增充值金额
      amountError: '',        // 新增金额错误提示
      // // 模拟数据
      // currentBills: [
      //   {
      //     name: '2023-08月账单',
      //     specialCost: 200.0,
      //     remark: '药品附加费用',
      //     stayCost: 1500.0,
      //     foodCost: 800.0,
      //     nursingCost: 2000.0,
      //     balance: 4500.0,
      //     createTime: '2023-08-31',
      //     totalCost: 4500.0,
      //   }
      // ],
      // historyBills: [
      //   {
      //     billNo: 'BILL202307',
      //     name: '2023-07月账单',
      //     specialCost: 150.0,
      //     stayCost: 1500.0,
      //     foodCost: 800.0,
      //     nursingCost: 2000.0,
      //     createTime: '2023-07-31',
      //     totalCost: 4450.0
      //   }
      // ]
    }
  },
  computed: {
    paymentButtonText() {
      if (this.currentBills.length === 0) return '暂无账单'
      return this.currentBills[0].balance < 0 ? '去支付' : '已缴清上月扣款'
    },
    isPaymentDisabled() {
      return this.currentBills.length === 0 || this.currentBills[0].balance >= 0
    }
  },
  onShow() {
    // 获取所有老人的账单信息
    this.getAllBillInfo();
  },
  methods: {
    // 切换标签页
    handleTabChange(index) {
      this.activeTab = index
    },
    // 支付账单
    async handlePayment() {
      const res = await payBillOrRecharge(uni.getStorageSync('elderId'), this.currentBills[0].totalCost);
      if (res.code === 200) {
        uni.showToast({
          title: "支付成功",
          icon: "success"
        });
        this.getAllBillInfo();
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none"
        });
      }

    },
    // 获取所有账单信息
    async getAllBillInfo() {
      try {
        const elderId = uni.getStorageSync('elderId')
        const res = await getAllFeeDetails(elderId)

        if (res.data && res.data.length > 0) {
          // 处理数据格式
          const processedData = res.data.map(item => ({
            ...item,
            yearMonth: this.getYearMonth(item.paymentDate),
            totalCost: item.nursingCost + item.stayCost + item.foodCost + item.specialCost
          }))

          // 按时间倒序排序
          processedData.sort((a, b) =>
            new Date(b.paymentDate) - new Date(a.paymentDate)
          )

          // 分离当前账单和历史账单
          const now = new Date()
          const currentMonth = now.getMonth() + 1
          const currentYear = now.getFullYear()

          // 查找最新未支付的账单
          const latestUnpaid = processedData.find(item => item.balance < 0)

          this.currentBills = latestUnpaid ? [latestUnpaid] : []
          this.historyBills = processedData.filter(item =>
            item !== latestUnpaid
          )

          // 更新账户余额
          if (processedData.length > 0) {
            this.accountBalance = processedData[0].balance
          }
        }
      } catch (error) {
        console.error("获取账单失败:", error)
        uni.showToast({ title: '获取账单失败', icon: 'none' })
      }
    },
    // 从日期字符串提取年月
    getYearMonth(dateStr) {
      if (!dateStr) return ''
      const [datePart] = dateStr.split(' ')
      const [year, month] = datePart.split('-')
      return `${year}-${month.padStart(2, '0')}`
    },
    // 关闭账单详情
    closeShowDetail() {
      this.showDetail = false
    },
    // 显示账单详情
    showBillDetail(bill) {
      this.currentBill = bill
      this.showDetail = true
    },
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    // 新增充值处理方法
    async handleRecharge() {
      try {
        if (!this.validateAmount()) return
        const res = await payBillOrRecharge(uni.getStorageSync('elderId'), Number(this.rechargeAmount));
        console.log(res);
        
        if (res.code === 200) {
          uni.showToast({
            title: '充值成功',
            icon: 'success'
          })
          this.getAllBillInfo();
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      } catch (error) {
        uni.showToast({
          title: '充值失败',
          icon: 'none'
        })
      } finally {
        this.showRecharge = false
        this.rechargeAmount = ''
      }

    },
    // 新增金额验证方法
    validateAmount() {
      const amount = Number(this.rechargeAmount)
      if (!amount || amount <= 0) {
        this.amountError = '请输入有效的充值金额'
        return false
      }
      if (amount > 100000) {
        this.amountError = '单次充值金额不能超过100,000元'
        return false
      }
      this.amountError = ''
      return true
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 20rpx;
}

.content {
  margin-top: 30rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin: 10rpx 0;

  text {
    flex: 1;
    font-size: 12px;
    color: #909399;
  }
}

.remark {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 10rpx;
}

.pay-button {
  margin-top: 30rpx;
}

.popup-content {
  padding: 40rpx;
  width: 600rpx;

  .title {
    text-align: center;
    margin-bottom: 30rpx;
  }
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin: 15rpx 0;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #eee;

  &:last-child {
    border-bottom: none;
  }
}

.time {
  color: #909399;
  font-size: 12px;
}

/* 新增充值样式 */
.recharge-btn {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 160rpx;
  height: 80rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  z-index: 999;
}

.balance-text {
  text-align: center;
  margin: 20rpx 0;
  color: #2979ff;
  font-weight: 500;
}

.balance-status {
  margin-top: 10rpx;
  color: #2979ff;
  font-size: 14px;
  font-weight: bold;
}

.recharge-popup {
  padding: 40rpx;
  width: 560rpx;

  .title {
    text-align: center;
    margin-bottom: 30rpx;
  }

  .input-amount {
    margin: 30rpx 0;
    font-size: 36rpx;

    /deep/ .u-input__content__prefix {
      margin-right: 20rpx;
    }
  }

  .confirm-btn {
    margin-top: 40rpx;
  }
}
</style>